import cv2
import re
import numpy as np
import base64


def read_img_base64(base64str):
    """Read image from base64 string
    """
    #check if contains javascript
    # print(re.sub('^data.*?;base64,', '', base64str))
    image_data = base64.b64decode(re.sub('^data:image/.+;base64,', '', base64str))

    nparr = np.fromstring(image_data, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\
        .astype(np.float32)
    return img


def read_img_blob(im_str):
    """Read image from base64 string
    """
    #check if contains javascript
    # arr = np.asarray(bytearray(im_str), dtype=np.uint8)
    arr = np.fromstring(im_str, np.uint8)
    # img = cv2.imdecode(arr,-1) # 'load it as it is'
    img = cv2.imdecode(arr, cv2.IMREAD_COLOR)\
        .astype(np.float32)
    return img


def jpeg_to_base64(img_file):
    img = open(img_file, 'rb').read()

    base64_str = base64.b64encode(img).decode('utf-8')

    return base64_str


if __name__ == '__main__':

    print(read_img_base64(open('/home/alpha/ML/test_img.txt').read()))
    base64_str = jpeg_to_base64('/home/alpha/ML/p1.jpg')
    print(read_img_base64(base64_str))
